<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="商品缩略图" prop="sysFileId" required>
                <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="1" :show-progress="false"
                          @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
            </u-form-item>
            <u-form-item label="编码" prop="code" required>
                <u-input v-model="validateForm.value.code" placeholder="请输入编码"/>
            </u-form-item>
            <u-form-item label="名称" prop="name" required>
                <u-input v-model="validateForm.value.name" placeholder="请输入名称"/>
            </u-form-item>
            <u-form-item label="成本价" prop="costPrice">
                <u-input v-model="validateForm.value.costPrice" placeholder="请输入成本价"/>
            </u-form-item>
            <u-form-item label="价格" prop="price" required v-if="'2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) === -1">
                <u-input v-model="validateForm.value.price" placeholder="请输入价格"/>
            </u-form-item>
            <u-form-item label="市场价" prop="marketPrice" required>
                <u-input v-model="validateForm.value.marketPrice" placeholder="请输入市场价"/>
            </u-form-item>
            <u-form-item label="库存数量" prop="stockNumber" required>
                <u-input v-model="validateForm.value.stockNumber" placeholder="请输入库存数量"/>
            </u-form-item>
            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>

            <div v-if="'2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) !== -1">
                <u-card :title="'客户类型价格'" :full="true">
                    <view class="" slot="body">
                        <u-form-item :label="item.name" :label-width="300" :prop="item.id" required v-for="(item, index) of tbCommunityUserTypeList"
                                     :key="item.id">
                            <u-input v-model="validateForm.value[item.id]" placeholder="请输入价格"/>
                        </u-form-item>
                    </view>
                </u-card>
            </div>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>
    </view>
</template>

<script>
    import {CommonService} from "@/dev/services/common.service";
    import {SysFileService} from "@/dev/services/sys-file.service";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {QiniuCloudUtil} from "@/dev/core/utils/qiniu-cloud.util";
    import {TbGoodsSpecificationService} from "@/dev/services/tb-goods-specification.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {TbCommunityUserTypeService} from "@/dev/services/tb-community-user-type.service";

    export default {
        data() {
            return {
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        goodsId: null,
                        sysFileId: '',  // 图片sysFile.id
                        code: '',
                        name: '',
                        costPrice: '0',
                        price: '',
                        marketPrice: '',
                        stockNumber: '',
                        displayOrder: '',
                        tbGoodsSpecificationUserTypeList: [],
                    },
                    rules: {
                        sysFileId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        code: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        "tableName": "tb_goods_specification",
                                        "fieldList": [
                                            {"fieldName": "goods_id", "fieldValue": this.validateForm.value.goodsId},
                                            {"fieldName": "code", "fieldValue": value},
                                        ],
                                        "excludeId": null
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('输入编号已存在！'))
                                        } else {
                                            callback()
                                        }
                                    })
                                }
                            }
                        ],
                        name: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        costPrice: [
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ],
                        price: [
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    // 公司模式
                                    if ('2,3,4'.indexOf(this.globalVariable.userInfo.tbCommunity.type) !== -1) {
                                        callback()
                                    } else {
                                        if (!value) {
                                            callback(new Error('必填项！'));
                                            return false;
                                        }
                                        let reg = /^[0-9]+(.[0-9]{1,2})?$/;
                                        if (!reg.test(value)) {
                                            callback(new Error('请输入有效的价格！'));
                                            return false;
                                        }
                                        callback()
                                    }
                                }
                            }
                        ],
                        marketPrice: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ],
                        stockNumber: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]*$/, message: '请输入有效的数量!', trigger: ['change', 'blur']}
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                },
                tbCommunityUserTypeList: []
            }
        },
        onReady() {
            const _self = this;
            this.validateForm.value.goodsId = this.urlParams.goodsId;

            if ('2,3,4'.indexOf(_self.globalVariable.userInfo.tbCommunity.type) !== -1) {
                new TbCommunityUserTypeService().findTbCommunityUserTypeList({
                    communityId: _self.globalVariable.userInfo.tbCommunity.id
                }).then(result => {
                    result.forEach(item => {
                        _self.validateForm.value[item.id] = '0';

                        _self.validateForm.rules[item.id] = [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ];
                    });

                    _self.tbCommunityUserTypeList = result;
                    console.log(_self.validateForm);
                    _self.$refs.validateFormRef.setRules(_self.validateForm.rules);
                    _self.$forceUpdate()
                });
            }
        },
        methods: {
            onRemove($event) {
                console.log($event);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.validateForm.value.sysFileId
                }).then(result => {
                    _self.validateForm.value.sysFileId = '';
                    CommonUtil.toast("图片删除成功");
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[$event.length - 1].file.path).then(result => {
                    if (result.status === "success") {
                        _self.validateForm.value.sysFileId = result.id;
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定

                                    _self.validateForm.value.tbGoodsSpecificationUserTypeList = [];
                                    _self.tbCommunityUserTypeList.forEach(item => {
                                        _self.validateForm.value.tbGoodsSpecificationUserTypeList.push({
                                            goodsId: _self.validateForm.value.goodsId,
                                            goodsSpecificationId: _self.validateForm.value.id,
                                            communityUserTypeId: item.id,
                                            price: _self.validateForm.value[item.id],
                                        });
                                    });

                                    new TbGoodsSpecificationService().saveTbGoodsSpecification(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功').then(result => {
                                            setTimeout(() => {
                                                _self.objParams();
                                            }, 500);
                                        });
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
